/**
 * Copyright 2014,Peak Tai 台俊峰(taijunfeng_it@sina.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * 		http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cenluan.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.jfinal.kit.StrKit;

public class OssManager {
	/**
	 * 客户端
	 */
	private static OSSClient client;

	static {
		client = new OSSClient(Profiles.getOssAccessKeyId(),
				Profiles.getOssAccessKeySecret());
	}

	public static OSSClient getClient() {
		return client;
	}

	/**
	 * 保存图片
	 * 
	 * @param input
	 *            输入流
	 * @param metadata
	 *            元数据
	 * @param key
	 *            文件的唯一标识名称，可不包含后缀
	 */
	public static void saveImage(InputStream input, ObjectMetadata metadata,
			String key) {
		client.putObject(Profiles.getOssImageBucket(), key, input, metadata);
	}

	/**
	 * 保存图片
	 * 
	 * @param file
	 * @param key
	 */
	public static void saveImage(File file, String key) {
		ObjectMetadata metadata = new ObjectMetadata();
		metadata.setContentLength(file.length());
		try {
			saveImage(new FileInputStream(file), metadata, key);
		} catch (FileNotFoundException e) {
			throw new IllegalArgumentException("file not found", e);
		}
	}

	/**
	 * 获取图片地址，获取后的地址通过拼接参数可实现压缩
	 * 
	 * @param key
	 * @return
	 */
	public static String getImageUrl(String key) {
		if (StrKit.isBlank(key)) {
			return null;
		}
		return "http://" + Profiles.getOssImageDomain() + "/" + key;
	}

	/**
	 * 删除图片
	 * 
	 * @param key
	 */
	public static void deleteImage(String key) {
		if (StrKit.isBlank(key)) {
			return;
		}
		client.deleteObject(Profiles.getOssImageBucket(), key);
	}

}
